//
//  RecommendViewController.m
//  PTravel
//
//  Created by dllo on 15/11/13.
//  Copyright © 2015年 李涵. All rights reserved.
//

#import "RecommendViewController.h"


@interface RecommendViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,NextDelegate,HeadViewDelegate>
@property (retain, nonatomic)NSMutableArray *slideArr;
@property (retain, nonatomic)NSMutableArray *slideArr1;
@property (retain, nonatomic)NSMutableArray *nextArr;
@property (retain, nonatomic)NSMutableArray *arr;
@property (retain, nonatomic)UITableView *myTableView;
@property (retain, nonatomic)YYCycleScrollView *cycleScrollView;
@property (retain, nonatomic)HeadView *headV;
@property (retain, nonatomic)UICollectionView *collection;
@property (retain, nonatomic)NextTableViewCell *cell;

@property (retain, nonatomic)UILabel *headLabel;
@property (retain, nonatomic)UILabel *headLabell;
@end

@implementation RecommendViewController

- (void)dealloc
{
    [_headLabell release];
    [_headLabel release];
    [_slideArr release];
    [_slideArr1 release];
    [_nextArr release];
    [_arr release];
    [_myTableView release];
    [_cycleScrollView release];
    [_headV release];
    [_collection release];
    [_cell release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    //夜间模式判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor:) name:@"night" object:nil];
    
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isTravel"] length] != 0) {
        self.headV.travelLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"isTravel"];
    }
}

- (void)changeColor:(NSNotificationCenter *)notification
{
     self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:TEXTCOLOR};
    self.myTableView.backgroundColor = CELLCOLOR;
    self.navigationController.navigationBar.barTintColor = BARCOLOR;
    [self.myTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    self.headLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, BOUNDS.size.width-15, 28)];
    [_headLabel release];
    self.headLabell = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, BOUNDS.size.width-15, 28)];
    [_headLabell release];
    
    self.arr = [NSMutableArray array];
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, BOUNDS.size.height) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    [self.myTableView registerClass:[NextTableViewCell class] forCellReuseIdentifier:@"NextTableViewCell"];
    [self.myTableView registerClass:[HotTableViewCell class] forCellReuseIdentifier:@"HotTableViewCell"];
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.backgroundColor = CELLCOLOR;
    [_myTableView release];
    
    // 集成上拉下拉功能
    self.isUpLoading = NO;
    [self addHeader];
    [self addFooter];
   
    self.navigationController.navigationBar.barTintColor = [Night barColor];
    self.navigationItem.title = @"推荐";
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:TEXTCOLOR};
    
    
}



#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block RecommendViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc getdata:vc.nextPage];//重新请求数据
        [vc getHotData:vc.nextPage];
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myTableView headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
   
    //    __unsafe_unretained typeof(self) vc = self;
    //__unsafe_unretained ViewController *vc = self;
     __unsafe_unretained RecommendViewController *vc = self;
    // 添加上拉刷新尾部控件
    [self.myTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.nextPage ++;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc getHotData:vc.nextPage];
        
    }];
}

- (void)buttonAction
{
    
}


#pragma mark === 轮播图方法
- (void)getdata:(NSInteger)page
{
    self.cycleScrollView = [[YYCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, 190) animationDuration:2.0];
    self.slideArr = [NSMutableArray array];
    self.slideArr1 = [NSMutableArray array];
    [AppTools getAFN:[NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/entry?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88255639279708&lon=121.5396443687879&page=%ld&track_app_channel=App%%2520Store&track_app_version=6.8&track_device_info=iPhone7%%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%%25209.1&v=1", (long)page] block:^(id result) {
        
        NSMutableDictionary *bigDic = result;
        NSMutableDictionary *smallDic = [bigDic objectForKey:@"data"];
        self.slideArr = [smallDic objectForKey:@"slide"];
        NSMutableArray *viewArray = [[NSMutableArray alloc] init];
        for (NSMutableDictionary *dic in self.slideArr) {
            NSString *imageStr = [dic objectForKey:@"photo"];
            
            UIImageView *tempImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, 190)];
            NSURL *url = [NSURL URLWithString:imageStr];
            [tempImageView sd_setImageWithURL:url placeholderImage:IMAGE];
            
            tempImageView.contentMode = UIViewContentModeScaleAspectFill;
            tempImageView.clipsToBounds = true;
            [viewArray addObject:tempImageView];
            
            Slider *slider = [[Slider alloc] init];
            [slider setValuesForKeysWithDictionary:dic];
            [self.slideArr1 addObject:slider];
            
        }
        for (int i = 0; i < self.slideArr.count; i++) {
        }
        [self.cycleScrollView setFetchContentViewAtIndex:^UIView *(NSInteger(pageIndex)) {
            return [viewArray objectAtIndex:pageIndex];
        }];
        [self.cycleScrollView setTotalPagesCount:^NSInteger{
            return self.slideArr.count;
        }];
        [self.cycleScrollView setTapActionBlock:^(NSInteger(pageIndex)) {
            
            
            NextDetailViewController *detail = [[NextDetailViewController alloc] init];
            [self.navigationController pushViewController:detail animated:YES];
            Slider *slider = [self.slideArr1 objectAtIndex:pageIndex];
            detail.url = slider.url;
            NSLog(@"点击的相关的页面%ld",(long)pageIndex);
            
        }];
        
        [self.myTableView headerEndRefreshing];
    }];
    

}

#pragma mark === 热点推荐获取数据
- (void)getHotData:(NSInteger)page
{
    
    
    
    [AppTools getAFN:[NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&lat=38.88270153206485&lon=121.5395785062165&page=%ld&track_app_channel=App%%2520Store&track_app_version=6.8&track_device_info=iPhone7%%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%%25209.1&type=index&v=1", (long)page] block:^(id result) {
      
        
        if (self.isUpLoading == NO) {
            [self.arr removeAllObjects];
            
        }

        NSMutableDictionary *bigDic = result;
        NSMutableArray *arr1 = [bigDic objectForKey:@"data"];
        for (NSMutableDictionary *dic in arr1) {
            HotTravel *hotT = [[HotTravel alloc] init];
            [hotT setValuesForKeysWithDictionary:dic];
            [self.arr addObject:hotT];
        }
        self.headV = [[HeadView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, 300)];
        
        self.headV.headViewDelegate = self;
        [self.headV addSubview:self.cycleScrollView];
        self.myTableView.tableHeaderView = self.headV;
        [_headV release];
        self.myTableView.tableHeaderView = self.headV;
        [self.myTableView reloadData];
        [self.myTableView footerEndRefreshing];
    }];
}

#pragma mark === 点击看锦囊进入(方法实现)
- (void)lookBook
{
    BookViewController *book = [[BookViewController alloc] init];
    [self.navigationController pushViewController:book animated:YES];
}


#pragma mark === 点击抢折扣进入（方法实现）
- (void)discount
{
    DiscountViewController *dis = [[DiscountViewController alloc] init];
    [self.navigationController pushViewController:dis animated:YES];
}

#pragma mark === 点击旅途中进入（方法实现）
- (void)traveling
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isTravel"] length] == 0) {
        TravelingViewController *travel = [[TravelingViewController alloc] init];
        UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:travel];
        [self presentViewController:na animated:YES completion:^{
            
            
        }];
    }else{
        
            CityViewController *city = [[[CityViewController alloc] init] autorelease];
            UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:city];
            [self presentViewController:na animated:YES completion:^{
                
                
            }];
            city.lat = [[NSUserDefaults standardUserDefaults] objectForKey:@"lat"];
            city.lng = [[NSUserDefaults standardUserDefaults] objectForKey:@"lng"];

    }
    
}

#pragma mark === 查看更多精彩专题
- (void)moreStation
{
    ThemeViewController *theme = [[ThemeViewController alloc] init];
    [self.navigationController pushViewController:theme animated:YES];
}

#pragma mark === tableView方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return self.arr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (indexPath.section == 0) {
        self.cell = [tableView dequeueReusableCellWithIdentifier:@"NextTableViewCell" forIndexPath:indexPath];
        [self.cell addSubview:self.collection];
        self.cell.nextDelegate = self;
        self.cell.backgroundColor = CELLCOLOR;
        return self.cell;

    }else{
        HotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HotTableViewCell" forIndexPath:indexPath];
        cell.hotTravel = [self.arr objectAtIndex:indexPath.row];
        cell.backgroundColor = CELLCOLOR;
        return cell;
    }
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 270;
    }else{
        
        return 90;
    }
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"发现下一站";
    }else{
        return @"热点推荐";
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, 28)];
    headV.backgroundColor = CELLCOLOR;
    if (section == 0) {
        self.headLabel.text =  @"发现下一站";
        self.headLabel.textColor = TEXTCOLOR;
        [headV addSubview:self.headLabel];
    }else{
        self.headLabell.text = @"热点推荐";
        self.headLabell.textColor = TEXTCOLOR;
        [headV addSubview:self.headLabell];
    }
    return headV;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 25;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NextDetailViewController *detail = [[NextDetailViewController alloc] init];
    [self.navigationController pushViewController:detail animated:YES];
    HotTravel *hot = [self.arr objectAtIndex:indexPath.row];
    detail.url = hot.view_url;
    
}
#pragma mark ** 点击下一站跳转
- (void)passStation:(Recommend *)recommed
{

    NextDetailViewController *detail = [[NextDetailViewController alloc] init];
    detail.url = recommed.url;
    detail.titleName = recommed.title;
    [self.navigationController pushViewController:detail animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
